<template>
  <div class="goods-detail">
    <!-- 顶部导航栏 -->
    <Navbar />
    
    <div class="container" v-loading="loading">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
      </el-breadcrumb>

      <div v-if="!loading && goodsDetail" class="detail-content">
        <div class="detail-main">
          <!-- 左侧：商品图片 -->
          <div class="image-section">
            <img :src="getImageUrl(goodsDetail.image)" class="main-image" />
          </div>

          <!-- 右侧：商品信息 -->
          <div class="info-section">
            <h1 class="goods-title">{{ goodsDetail.goodsName }}</h1>
            
            <div class="price-section">
              <span class="label">价格：</span>
              <span class="price">¥{{ goodsDetail.price }}</span>
            </div>

            <div class="sales-info">
              <span class="sales">销量：{{ goodsDetail.sales }}</span>
            </div>

            <el-divider />

            <div class="description">
              <h3>商品描述</h3>
              <p>{{ goodsDetail.desc }}</p>
            </div>

            <div class="actions">
              <el-button 
                type="danger" 
                size="large" 
                :icon="goodsDetail.ifCollect ? StarFilled : Star"
                @click="handleToggleCollect"
              >
                {{ goodsDetail.ifCollect ? '已收藏' : '收藏' }}
              </el-button>
              
              <el-button 
                type="primary" 
                size="large"
                :loading="addingToCart"
                @click="addToCart"
              >
                {{ addingToCart ? '添加中...' : '加入购物车' }}
              </el-button>
              
              <el-button 
                type="warning" 
                size="large"
                @click="buyNow"
              >
                立即购买
              </el-button>
            </div>
          </div>
        </div>

        <!-- 商品评价 -->
        <div class="comments-section">
          <div class="section-header">
            <h2 class="section-title">商品评价</h2>
            <el-button 
              v-if="userStore.isLoggedIn()" 
              type="primary"
              @click="showCommentDialog = true"
            >
              发表评价
            </el-button>
          </div>
          
          <div v-loading="commentsLoading" class="comments-list">
            <el-empty v-if="!commentsLoading && commentList.length === 0" description="暂无评价" />

            <div 
              v-for="comment in commentList" 
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-header">
                <img :src="getImageUrl(comment.avatar)" class="user-avatar" />
                <div class="user-info">
                  <div class="user-name">{{ comment.userName }}</div>
                  <el-rate 
                    v-model="comment.rating" 
                    disabled 
                    size="small"
                  />
                </div>
                <div class="comment-time">{{ formatDateTime(comment.commentTime) }}</div>
              </div>

              <div class="comment-content">
                {{ comment.content }}
              </div>

              <div v-if="comment.picture" class="comment-image">
                <el-image 
                  :src="getImageUrl(comment.picture)" 
                  :preview-src-list="[getImageUrl(comment.picture)]"
                  fit="cover"
                  style="width: 120px; height: 120px; border-radius: 4px;"
                />
              </div>
            </div>
          </div>

          <!-- 评价分页 -->
          <el-pagination
            v-if="commentTotal > 0"
            class="comment-pagination"
            v-model:current-page="commentPageNum"
            :page-size="commentPageSize"
            :total="commentTotal"
            layout="prev, pager, next"
            small
            @current-change="loadComments"
          />
        </div>
      </div>

      <el-empty v-if="!loading && !goodsDetail" description="商品不存在" />
    </div>

    <!-- 评价对话框 -->
    <CommentDialog 
      v-model="showCommentDialog" 
      :order="mockOrderForComment"
      @success="handleCommentSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getGoodsDetail } from '@/api/goods'
import { addOrRemoveGoods } from '@/api/cart'
import { getGoodsComments } from '@/api/comment'
import { toggleCollect as toggleCollectApi } from '@/api/collect'
import { ElMessage } from 'element-plus'
import Navbar from '@/components/Navbar.vue'
import CommentDialog from '@/components/CommentDialog.vue'
import { getFileUrl } from '@/api/file'
import { Star, StarFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const goodsDetail = ref(null)
const loading = ref(false)
const addingToCart = ref(false)

// 评价相关
const commentList = ref([])
const commentsLoading = ref(false)
const commentPageNum = ref(1)
const commentPageSize = ref(5)
const commentTotal = ref(0)
const showCommentDialog = ref(false)

// 为评价对话框创建模拟订单对象
const mockOrderForComment = computed(() => {
  if (!goodsDetail.value) return null
  
  return {
    id: 0, // 没有订单ID，这是直接在商品详情页评价
    goodsId: goodsDetail.value.goodsId,
    goodsName: goodsDetail.value.goodsName,
    picture: goodsDetail.value.image
  }
})

// 获取商品详情
const loadGoodsDetail = async () => {
  const goodsId = route.params.goodsId
  if (!goodsId) return

  loading.value = true
  try {
    const data = await getGoodsDetail(parseInt(goodsId))
    goodsDetail.value = data
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 切换收藏状态
const handleToggleCollect = async () => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    userStore.openLoginDialog()
    return
  }

  try {
    await toggleCollectApi(goodsDetail.value.goodsId)
    
    // 切换收藏状态
    goodsDetail.value.ifCollect = !goodsDetail.value.ifCollect
    
    ElMessage.success(goodsDetail.value.ifCollect ? '收藏成功' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
  }
}

// 加入购物车
const addToCart = async () => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  addingToCart.value = true
  try {
    await addOrRemoveGoods({
      goodsId: parseInt(route.params.goodsId),
      ifAdd: true
    })
    ElMessage.success('已加入购物车')
  } catch (error) {
    console.error('加入购物车失败:', error)
  } finally {
    addingToCart.value = false
  }
}

// 立即购买
const buyNow = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  // 跳转到订单确认页
  router.push({
    path: '/order-confirm',
    query: {
      goodsId: route.params.goodsId,
      goodsNum: 1
    }
  })
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

// 加载商品评价
const loadComments = async () => {
  const goodsId = route.params.goodsId
  if (!goodsId) return

  commentsLoading.value = true
  try {
    const data = await getGoodsComments({
      goodsId: parseInt(goodsId),
      pageNum: commentPageNum.value,
      pageSize: commentPageSize.value
    })
    commentList.value = data.list || []
    commentTotal.value = data.total || 0
  } catch (error) {
    console.error('获取评价失败:', error)
  } finally {
    commentsLoading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 评价成功
const handleCommentSuccess = () => {
  showCommentDialog.value = false
  ElMessage.success('评价成功')
  // 重新加载评价列表
  commentPageNum.value = 1
  loadComments()
}

onMounted(() => {
  loadGoodsDetail()
  loadComments()
})
</script>

<style scoped>
.goods-detail {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.detail-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
}

.detail-main {
  display: flex;
  gap: 40px;
}

.image-section {
  flex: 0 0 400px;
}

.main-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.info-section {
  flex: 1;
}

.goods-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.price-section {
  background: #f7f7f7;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.label {
  font-size: 14px;
  color: #666;
}

.price {
  font-size: 32px;
  font-weight: bold;
  color: #ff4d4f;
  margin-left: 10px;
}

.sales-info {
  margin-bottom: 20px;
}

.sales {
  font-size: 14px;
  color: #999;
  margin-right: 20px;
}

.description {
  margin: 20px 0;
}

.description h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.description p {
  font-size: 14px;
  color: #666;
  line-height: 1.8;
}

.actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.actions .el-button {
  flex: 1;
}

/* 评价区域 */
.comments-section {
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #e8e8e8;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.comments-list {
  min-height: 200px;
}

.comment-item {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.comment-time {
  font-size: 13px;
  color: #999;
}

.comment-content {
  font-size: 14px;
  line-height: 1.8;
  color: #666;
  margin-bottom: 12px;
}

.comment-image {
  margin-top: 12px;
}

.comment-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .detail-main {
    flex-direction: column;
  }

  .image-section {
    flex: 1;
  }

  .actions {
    flex-direction: column;
  }

  .actions .el-button {
    width: 100%;
  }
}
</style>
